const { app, BrowserWindow, Menu, globalShortcut, session, ipcMain } = require('electron');
const path = require('path');
require('../communicate/bili.js');
require('../communicate/operation.js');

let mainWindow;
const isPackaged = app.isPackaged;
Menu.setApplicationMenu(null);
exports.createWindow = () => {
  mainWindow = new BrowserWindow({
    // 默认窗口标题，如果由loadURL()加载的HTML文件中含有标签<title>，此属性将被忽略。
    // title: "实验",
    width: 1000,
    height: 670,
    icon: path.resolve(__dirname, '../../build/icon.ico'),
    show: false,
    frame: false,
    vibrancy: 'light',
    hasShadow: true,
    webPreferences: {
      preload: path.join(__dirname, '../preload.js'),
    },
  });
  if (!isPackaged) {
    mainWindow.loadURL('http://localhost:9999/#/');
    // 注册全局 F2 快捷键
    const ret = globalShortcut.register('CommandOrControl+F12', () => {
      if (mainWindow.webContents.isDevToolsOpened()) mainWindow.webContents.closeDevTools();
      else mainWindow.webContents.openDevTools();
    });
    if (!ret) {
      console.log('快捷键注册失败');
    }
  } else {
    mainWindow.loadURL(`file://${path.join(__dirname, '../../dist/index.html')}`);
    // 将 file://example.com/xxx 的 文件改为 https 协议
    // session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
    //   if (/^file:\/\/example\.com\//.test(details.url)) {
    //     callback({ redirectURL: details.url.replace(/^file/, 'https') });
    //   } else {
    //     callback(details);
    //   }
    // });
  }
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });
  return mainWindow;
};

ipcMain.handle('miximize', () => {
  mainWindow.minimize();
});
ipcMain.handle('maximize', () => {
  if (mainWindow.isMaximized()) mainWindow.restore();
  else mainWindow.maximize();
});
ipcMain.handle('closeWindow', () => {
  app.quit();
});
